<template>
  <div class="admin-management">
    <!-- 搜索和操作区域 -->
    <div class="toolbar">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索管理员账号或姓名"
          clearable
          style="width: 250px; margin-right: 10px;"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <!-- 只有超级管理员才能看到添加按钮 -->
      <el-button v-if="isSuperAdmin" @click="handleAdd">添加管理员</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="filteredTableData"
        border    style="width: 100%; margin-top: 20px;"
        :default-sort="{ prop: 'admin_id', order: 'ascending' }"
    >
      <el-table-column
          prop="adminId"
          label="ID"
          width="80"
          sortable
      />
      <el-table-column
          prop="adminAccount"
          label="账号"
          width="150"
      />

      <el-table-column
          prop="adminRole"
          label="角色"
          width="100"
          :formatter="formatRole"
      />
      <el-table-column
          prop="adminName"
          label="姓名"
          width="120"
      />
      <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
      />
      <el-table-column
          prop="lastLoginTime"
          label="最后登录时间"
          width="180"
      />
      <el-table-column
          prop="status"
          label="状态"
          width="100"
          :formatter="formatStatus"
      />
      <el-table-column
          prop="resetPasswordTime"
          label="重置密码时间"
          width="180"
      />
      <el-table-column
          label="操作"
          width="180"
      >
        <template #default="scope">
          <!-- 只有超级管理员才能看到编辑和删除按钮 -->
          <el-button v-if="isSuperAdmin" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="isSuperAdmin" size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <!-- 普通管理员只能查看 -->
          <span v-if="!isSuperAdmin" class="text-gray-500">仅查看</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px;"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
    >
      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="100px"
      >
        <el-form-item label="账号" prop="admin_account">
          <el-input v-model="form.adminAccount" />
        </el-form-item>
        <el-form-item label="密码" prop="admin_password">
          <el-input v-model="form.adminPassword" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="admin_role">
          <el-select v-model="form.adminRole" placeholder="请选择角色">
            <el-option label="普通管理员" :value="1" />
            <el-option label="超级管理员" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="admin_name">
          <el-input v-model="form.adminName" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted,watch } from 'vue';
import axios from '@/utils/axios';
import { getCurrentUser, getAdminList, addAdmin, updateAdmin, deleteAdmin, type AdminInfo } from '@/api/admin';
import {ElMessageBox} from "element-plus";

// 表格数据
const tableData = ref<AdminInfo[]>([]);

// 当前用户信息
const currentUser = ref<any>(null);

// 权限控制
const isSuperAdmin = computed(() => {
  return currentUser.value?.admin_role === 2; // 2表示超级管理员
});

// 搜索关键词
const searchKeyword = ref('');

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
let searchTimer: any = null;
// 防抖搜索
watch(searchKeyword, (newVal, oldVal) => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    currentPage.value = 1
    loadAdminList()
  }, 300) // 300ms防抖延迟
})

// 简化后的表格数据（直接使用tableData，不再前端过滤）
const filteredTableData = computed(() => {
  return tableData.value || []
})



// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加管理员');
const form = reactive({
  adminId: 0,
  adminAccount: '',
  adminPassword: '',
  adminRole: 1,
  adminName: '',
  createTime: '',
  lastLoginTime: '',
  status: 1,
  resetPasswordTime: ''
});

// 表单验证规则
const rules = {
  adminAccount: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  adminPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  adminName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ]
};

// 表格列格式化函数
const formatRole = (row: any, column: any, cellValue: any) => {
  return cellValue === 1 ? '管理员' : '普通用户';
};

const formatStatus = (row: any, column: any, cellValue: any) => {
  return cellValue === 1 ? '启用' : '禁用';
};

// 方法
const handleSearch = () => {
  currentPage.value = 1;
  loadAdminList()
};

const handleAdd = () => {
  dialogTitle.value = '添加管理员';
  form.adminAccount = '';
  form.adminPassword = '';
  form.adminRole = 1;
  form.adminName = '';
  form.status = 1;
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  dialogTitle.value = '编辑管理员';
  Object.assign(form, row);
  dialogVisible.value = true;
};



const handlePageChange = (page: number) => {
  currentPage.value = page;
  loadAdminList()
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const submitForm = async () => {
  try {
    if (form.adminId === 0) {
      // 添加管理员
      await addAdmin({
        adminAccount: form.adminAccount,
        adminPassword: form.adminPassword,
        adminRole: form.adminRole,
        adminName: form.adminName,
        status: form.status
      });
      ElMessage.success('添加成功');
    } else {
      // 编辑管理员
      await updateAdmin({
        adminId: form.adminId,
        adminAccount: form.adminAccount,
        adminPassword: form.adminPassword,
        adminRole: form.adminRole,
        adminName: form.adminName,
        status: form.status
      });
      ElMessage.success('更新成功');
    }
    dialogVisible.value = false;
    await loadAdminList();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 加载管理员列表
const loadAdminList = async () => {
  try {
    const response = await getAdminList({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value
    });
    console.log(searchKeyword.value)
    console.log(response)
    if (response.code === 200) {
      tableData.value = response.data?.list || [];
      total.value = response.data?.total || 0;
      console.log(tableData.value)
      console.log(total.value)
    }
  } catch (error) {
    ElMessage.error('加载数据失败');
  }
};

// 获取当前用户信息
const loadCurrentUser = async () => {
  try {
    const response = await getCurrentUser();
    if (response.code === 200) {
      currentUser.value = response.data;
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败');
  }
};

// 删除管理员
const handleDelete = async (row: AdminInfo) => {
  try {
    await ElMessageBox.confirm('确定要删除这个管理员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await deleteAdmin(row.admin_id);
    ElMessage.success('删除成功');
    await loadAdminList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 页面初始化
onMounted(async () => {
  await loadCurrentUser();
  await loadAdminList();
});
</script>

<style scoped>
.admin-management {
  padding: 20px;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
}
</style>
